package com.health.mapp.impl;

import java.math.BigDecimal;
import java.util.List;

import net.sf.jsqlparser.expression.StringValue;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.health.db.model.CourseGoodsTemp;
import com.health.db.model.CourseShareRemark;
import com.health.db.model.CourseShareRemarkExample;
import com.health.db.model.GoodsGiftList;
import com.health.db.model.GoodsGiftListExample;
import com.health.db.model.GoodsListCouse;
import com.health.db.model.GoodsListExample;
import com.health.db.model.GoodsOrder;
import com.health.db.model.UserLIST;
import com.health.db.model.VersionControlExt;
import com.health.db.service.sm.IGoodsGiftListService;
import com.health.db.service.sm.IGoodsListService;
import com.health.db.service.sm.IGoodsOrderService;
import com.health.db.service.sm.IVersionControlService;
import com.health.db.service.user.ICourseShareRemarkService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.Header;
import com.health.mapp.bean.QueryCourseGoodsReq;
import com.health.mapp.bean.QueryCourseGoodsResp;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.Response;
import com.health.mapp.utils.ResultCode;
import com.wxtools.api.IMiniService;
/**
 * 查看课程类商品
 * 
 * @author Yuchong
 *
 */
public class QueryCourseGoodsImpl implements ActionInterface {

	@Autowired
	private IGoodsListService goodsListService  ;
	@Autowired
	private IGoodsOrderService goodsOrderService;
	@Autowired
	private IUserLISTService userLISTService;
	@Autowired
    private IMiniService miniService;
	@Autowired
    private ICourseShareRemarkService courseShareRemarkService;
	@Autowired
    private IVersionControlService versionControlService;
	
	@Autowired
	private IGoodsGiftListService goodsGiftListService;
    
    
    private static String GOODS_ID = "61";
    
    /**
     * @param header 头部信息
     * 		 appId=40001
     * @param reqBean 请求对象
     * 
     */
	@Override
	public Response execute(Header header, Object reqBean) throws Exception {
		
		QueryCourseGoodsReq req = (QueryCourseGoodsReq) reqBean;
		QueryCourseGoodsResp _resp = new QueryCourseGoodsResp();
		
		String freeFalg="0";
		
		//初始化用户id
		Long userId = 0l;
	    String openId = req.getOpenId();
	    
	    String version=header.getVersion();
	    
	    String goodsId = req.getGoodsId();
	    if (StringUtils.isBlank(goodsId)||("undefined").equals(goodsId)) {
	    	goodsId = GOODS_ID;
		}

	    String inviterId = req.getInviterId();
	    //邀请链接
	    String path = req.getPath();
		if (StringUtils.isNotBlank(goodsId)&&StringUtils.isNotBlank(path)) {
			
			//userid入参
			if ( StringUtils.isNotBlank(req.getUserId())){
				userId= Long.valueOf(req.getUserId());
			}else if(StringUtils.isNotBlank(openId)){
				  List<UserLIST> userList= userLISTService.selectByWXOpenid(openId);
				  
				  if (userList.size()>0) {
					  userId = userList.get(0).getUserid();
				  }else{
					  _resp.setErrorCode(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS);
					  _resp.setErrorMsg(ResultCode.LOGIN_FAIL_MEMBER_IS_NOT_EXISTS_NOTE);
					  return _resp;
				  }
				
			}else{
				_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
				_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
				return _resp;
			}
			
			//查看之前是否已分享
			CourseShareRemarkExample shareRemarkExample = new CourseShareRemarkExample();
			shareRemarkExample.setGoodsId(Long.valueOf(goodsId));
			shareRemarkExample.setUserId(Long.valueOf(userId));
			List<CourseShareRemark> shareRemarkList =courseShareRemarkService.selectByExample(shareRemarkExample);
	
			if (shareRemarkList.size()>0) {
				
				CourseShareRemark remark = shareRemarkList.get(0);
				//取之前生成过的永久链接
				_resp.setMiNiShareUrl(remark.getShareImageUrl());
				_resp.setMiNiShareQRUrl(remark.getShareImageUrl());
				
				if (StringUtils.isNotBlank(inviterId)) {
					if (null==remark.getInviterId()||(remark.getInviterId().longValue()!=Long.valueOf(inviterId).longValue())) {
						
						CourseShareRemark updatebean = new CourseShareRemark();
						
						updatebean.setGoodsId(Long.valueOf(goodsId));
						updatebean.setUserId(Long.valueOf(userId));
						updatebean.setInviterId(Long.valueOf(inviterId));
						updatebean.setRecId(remark.getRecId());
						courseShareRemarkService.updateByPrimaryKeySelective(updatebean);
					}
					
				}
				
				
				
				
			}else{
				//新生成链接
				String shareImageUrl = miniService.createwxaqrcode(path, "430");
				
				//存储
				CourseShareRemark  courseShareRemarkBean = new CourseShareRemark();
				courseShareRemarkBean.setGoodsId(Long.valueOf(goodsId));
				courseShareRemarkBean.setUserId(Long.valueOf(userId));
				courseShareRemarkBean.setShareImageUrl(shareImageUrl);
				
				//插入邀请人
				if (StringUtils.isNotBlank(inviterId)) {
					courseShareRemarkBean.setInviterId(Long.valueOf(inviterId));
				}
			
				courseShareRemarkService.insert(courseShareRemarkBean);
				_resp.setMiNiShareUrl(shareImageUrl);
				_resp.setMiNiShareQRUrl(shareImageUrl);
			}
			
			GoodsListExample example = new GoodsListExample();
			example.setGoodsid(Long.valueOf(goodsId));
			//查询订单
			List<GoodsListCouse> list =  goodsListService.selectBySimpleCouse(example);
			CourseGoodsTemp courseGoods = new CourseGoodsTemp();
			if (list.size()==1) {
				GoodsListCouse temp = list.get(0);
			    BeanUtils.copyProperties(temp,courseGoods);
			    courseGoods.setCourseList(temp.getGoodsCourseItem());
			    courseGoods.setDetailPicList(temp.getDetailPicList());
			    
			    GoodsGiftListExample GoodsGiftListExample = new  GoodsGiftListExample();
			    GoodsGiftListExample.setGoodsId(Long.valueOf(goodsId));
			    
			    if (StringUtils.isEmpty(req.getChannel())||"null".equals(req.getChannel())) {
			    	GoodsGiftListExample.setChannel(String.valueOf("1"));
			    	
				}else{
					GoodsGiftListExample.setChannel(req.getChannel());
				}
			    
			    GoodsGiftList goodsGiftList=goodsGiftListService.selectByChannel(GoodsGiftListExample);
		    	courseGoods.setGiftList(goodsGiftList);
			    //测试
			/*    BigDecimal tempSalePrice = new BigDecimal(temp.getSaleListPrice());
			    if (tempSalePrice.compareTo(BigDecimal.ZERO)==0) {
			    	courseGoods.setIsOrder("1");
				}*/
		
			}else{
				_resp.setErrorCode(ResultCode.OPERATION_ORDER_ERROR_3018);
				_resp.setErrorMsg(ResultCode.OPERATION_ORDER_ERROR_3018_NOTE);
			}
			
			List<GoodsOrder>  goodsOrderList =goodsOrderService.selectByUserId(userId,Long.valueOf(goodsId));
			//判断是否购买成功
			if ((goodsOrderList.size()==0&&courseGoods.getFreeFlag().equals("1"))||
					new BigDecimal(courseGoods.getSaleListPrice()).compareTo(BigDecimal.ZERO)==0
					) {
					
				GoodsOrder goodsOrder = packageGoodsOrder(courseGoods, userId);
				courseGoods.setIsOrder("1");
				goodsOrderService.insert(goodsOrder);
			//暂不处理重复订购情况
			}else if (goodsOrderList.size()>=1) {
				courseGoods.setIsOrder("1");
			}
			_resp.setCourseGoods(courseGoods);
			
		}else{
			_resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
			_resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
			return _resp;
		}
		//分享页面头像
		_resp.setMiNiSaherIconUrl("video/60/image/icon.png");
		
		_resp.setMiNiShareLabelUrl("video/60/image/label.png");
		return _resp;
	}
	
	/**
	 * 免费课程自动订购
	 * @param courseGoods
	 * @param userId
	 * @return
	 */
	private GoodsOrder packageGoodsOrder(CourseGoodsTemp courseGoods ,Long userId){
		
		GoodsOrder goodsOrder = new GoodsOrder();
		goodsOrder.setGoodsid(Long.valueOf(courseGoods.getGoodsId()));
		
		goodsOrder.setGoodsName(courseGoods.getGoodsName());
		goodsOrder.setGoodsType(courseGoods.getTypeId());
		goodsOrder.setGoodsMeasure(courseGoods.getGoodsMeasure());
		goodsOrder.setTotal(new BigDecimal(courseGoods.getSalePrice()));
		
		goodsOrder.setOwnerid(userId);
		//goodsOrder.setOwenerName(req.getUserName());
		//已支付
		goodsOrder.setRunstatusid(Constant.CONSTANTS_ORDER_RUNSTATUS_ID_5);
		goodsOrder.setRunStatus(Constant.CONSTANTS_ORDER_RUNSTATUS_DES_5);
		goodsOrder.setPayFlag(String.valueOf(Constant.CONSTANTS_IS_PAYMENT_FALSE));
		goodsOrder.setPayTypeId(Constant.CONSTANTS_IS_PAYMENT_FALSE);
		goodsOrder.setRefBillid(Long.valueOf(-1));
		
		return goodsOrder;
		
	}
	
	private String checkForFreeVersion(Header head){
		
		String freeFalg="0";
		
		String appId= head.getAppId();
		
		String version = head.getVersion();
		
		if (StringUtils.isNotBlank(appId)&&appId.equals(Constant.MINI_PROGRAM_HEAD_APPID)) {
			
			//微信小程序对应标识
			String pattern = "2";// 操作系统标识
			
			VersionControlExt queryCondition = new VersionControlExt();
			queryCondition.setPattern(pattern);
			queryCondition.setVersion(version);

			//List<VersionControl> versionLastesList = versionControlService.selectLastestVersion(pattern,flag);
			
			/*if (null != versionLastesList && versionLastesList.size() == 1) {
				VersionControl versionLastesControl  = versionLastesList.get(0);
				resp.setVersion(versionLastesControl.getVersion());
				resp.setAppPath(versionLastesControl.getAppPath());
				resp.setReason(versionLastesControl.getReason());
				//resp.setUpdateTag(versionControl.getUpdateTag());
				resp.setLoadPage1(versionLastesControl.getLoadPage1());
				resp.setLoadPage2(versionLastesControl.getLoadPage2());
				resp.setLoadPage3(versionLastesControl.getLoadPage3());
				resp.setLoadPage4(versionLastesControl.getLoadPage4());
			}else {
				resp.setErrorCode(ResultCode.VERSION_UPDATE_VERSION_ERROR);
				resp.setErrorMsg(ResultCode.VERSION_UPDATE_NO_VERSION_ERROR_NOTE);
			}*/
		}else{
			
			return "1";
		}
		
		
	
		

		
		
		
		
		return freeFalg;
		
	}
	
	
	
	public IGoodsListService getGoodsListService() {
		return goodsListService;
	}
	public void setGoodsListService(IGoodsListService goodsListService) {
		this.goodsListService = goodsListService;
	}
	public IGoodsOrderService getGoodsOrderService() {
		return goodsOrderService;
	}
	public void setGoodsOrderService(IGoodsOrderService goodsOrderService) {
		this.goodsOrderService = goodsOrderService;
	}
	public IUserLISTService getUserLISTService() {
		return userLISTService;
	}
	public void setUserLISTService(IUserLISTService userLISTService) {
		this.userLISTService = userLISTService;
	}

	public IMiniService getMiniService() {
		return miniService;
	}
	public void setMiniService(IMiniService miniService) {
		this.miniService = miniService;
	}

	public ICourseShareRemarkService getCourseShareRemarkService() {
		return courseShareRemarkService;
	}

	public void setCourseShareRemarkService(
			ICourseShareRemarkService courseShareRemarkService) {
		this.courseShareRemarkService = courseShareRemarkService;
	}

	public IVersionControlService getVersionControlService() {
		return versionControlService;
	}

	public void setVersionControlService(
			IVersionControlService versionControlService) {
		this.versionControlService = versionControlService;
	}

	public IGoodsGiftListService getGoodsGiftListService() {
		return goodsGiftListService;
	}

	public void setGoodsGiftListService(IGoodsGiftListService goodsGiftListService) {
		this.goodsGiftListService = goodsGiftListService;
	}
	
	
	
}
